<?php
// Copyright 2019 Hackware SpA <human@hackware.cl>
// This file is part of "Hackware Web Services Wallet" and licensed under
// the terms of the GNU Affero General Public License version 3, or (at your
// option) a later version. You should have received a copy of this license
// along with the software. If not, see <https://www.gnu.org/licenses/>.

namespace Hawese\Wallet\Http\Controllers;

use Hawese\Wallet\Wallet;
use Hawese\Core\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class WalletController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function show(Request $request, string $user_uid)
    {
        $wallet = Wallet::find($user_uid);

        $this->authorize('read', $wallet);

        return $this->singleResponse($wallet);
    }
    
    public function store(Request $request)
    {
        $this->authorize('create', Wallet::class);

        $wallet = new Wallet(
            $request->only(['user_uid', 'currency_code'])
        );

        return app('db')->transaction(function () use ($wallet) {
            $wallet->insert();
            $wallet->initialTransaction();
            return $this->singleResponse($wallet);
        });
    }

    public function index(Request $request)
    {
        $this->authorize('list', Wallet::class);

        return $this->collectionResponse($request, Wallet::class);
    }
}
